package cn.niit.smbms.controller.admin;

import cn.niit.smbms.dao.UserMapper;
import cn.niit.smbms.entity.User;
import cn.niit.smbms.service.UserService;
import com.github.pagehelper.PageInfo;
import com.sun.deploy.net.MessageHeader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /*@Autowired
    private RoleService roleService;*/
    /**
     * 用户管理首页，主要显示用户列表
     * @return
     */
    @GetMapping("/user")
    public String index(Model model, User user){
        System.out.println("user = " + user);
        List<User> userList = userService.selectListByUser(user);
        /** 构造分页对象 */
        PageInfo<User> page = new PageInfo<User>(userList);
        log.info("分页结果对象PageInfor:{}", page);
        model.addAttribute("userList", userList);
        model.addAttribute("pageInfo", page);
        /** 在用户列表页的查询条件中动态加载角色列表 */
        //session.setAttribute("roleList", roleService.selectAll());
        return "user/list";
    }

    /**
     * 进入添加用户页面、或者是修改页面
     * /user/{id} 示例：/user/1
     * @param userId
     * @return
     */
    @GetMapping("/{id}")
    public String savaIndex(Model model, @PathVariable("id") Long userId){
        System.out.println(userId);
        User user = null;
        if(null != userId && userId >0){
            user = userService.selectById(userId);
        }else{
            user = new User();
        }
        model.addAttribute("user", user);
        return "user/add";
    }

    /**
     * 添加用户提交按钮后的请求方法
     * @param model
     * @param user
     * @param result
     * @param request
     * @return
     */
    @PostMapping("/user")
    public String add(Model model, @Validated User user, BindingResult result, HttpServletRequest request){
        log.info("待添加的用户信息： {}", user);
        if (result.hasErrors()){
            Map<String, String> errMap = new HashMap<>();
            for (FieldError error : result.getFieldErrors()) {
                log.warn("前端校验报错信息:", error.getField(), error.getDefaultMessage());
                errMap.put(error.getField(), error.getDefaultMessage());
            }
            model.addAttribute("errors", errMap);
            model.addAttribute("user", user);
            return "user/add";
        }
        User loginUser = (User) request.getSession().getAttribute("user");
        user.setCreateUserId(loginUser.getId());
        user.setCreateUserName(loginUser.getUserName());
        System.out.println("获取要添加的用户信息user：" + user);
        int rows = userService.add(user);
        //return index(model);
        return "redirect:/user/user";
    }

    /**
     * 更新用户信息
     * @param user
     * @param request
     * @return
     */
    @PutMapping("/user")
    public String update(User user, HttpServletRequest request){
        //拿用户数据
        User loginUser = (User) request.getSession().getAttribute("user");
        log.info("待更新的用户:{}", user);
        //为修改的记录赋值更新人信息
        user.setModifyUserId(loginUser.getId());
        user.setModifyUserName(loginUser.getUserName());
        user.setGmtCreate(new Date());
        int rows = userService.updateUser(user);
        log.info("被更新的记录数:{}", rows);
        if (rows <= 0){
            return "user/add";
        }
        return "redirect:/user/user";
    }

    /**
     * 删除用户
     * 映射路径：/user/{id}
     * @param userId
     * @return
     */
    @ResponseBody
    @DeleteMapping("/{id}")
    public String saveIndex(@PathVariable("id") Long userId){
        System.out.println(userId);
        int rows = 0;
        if (null != userId && userId > 0){
            rows = userService.deleteById(userId);
            if (rows > 0){
                return "true";
            }
        }
        return "false";
    }


}
